"""
File:      server.py
Author:    tcodi
Warranty:  AS IS, NO GUARANTEES TO ANY EFFECT.
License:   Lesser GNU Public License
"""

ServerAuth = "DeathByFlowers"

class User():
    server = False
    globalInput =""
    """
    There will be one of these for each user. It keeps track
    of the state for each user.  Such as need username, need pw,
    or logged in, and possibly exited.
    """  
    def __init__(self, name, sman):
        self.user=''
        self.pw=''
        self.state="username"
        self.name = name
        self.sman = sman

    def getState(self):
        return self.state

    def isServer(self):    
        return self.server

    def handleOutput(self):
        print self.state
        print self.globalInput
        if ("username" == self.state):
            self.state = "pw"   
            return "Username: "        
        elif ("pw" == self.state):
            return "Password: "
        elif ("login" == self.state):
            return "Logging into system[press enter to continue]...."
        elif ("loggedin" == self.state):
            self.state = "buffer"
            return "Welcome to RAW BBS!  If you need [help], just ask.\n"
        elif ("query" == self.state):
            print "query: " + self.globalInput
            self.state = "buffer"
            return self.sman.query(self.user, self.globalInput)   
        elif ("server" == self.state):
            return self.sman.getData()#self.sman.getData()
        elif ("buffer" == self.state):
            print "buffer: " + self.globalInput
            self.globalInput =""
            self.state = "query"
            return "Processing input [press enter to continue]..."#self.sman.query(self.user, self.globalInput)               

    def handleInput(self, inputStr, server_name):
        inputStr = inputStr.rstrip()
        if inputStr:
            self.globalInput = inputStr                
            if ("pw" == self.state):
                if (ServerAuth == inputStr):
                    print "This is a Server"  
                    self.server = True                  
                    self.state = "server"
                else:
                    self.user = inputStr
                    self.state = "login"
            elif ("login" == self.state):
                self.pw = inputStr
                self.__testLogin__()            
            elif ("server" == self.state):
                print "codis stuff: "+inputStr
                self.sman.addData(inputStr,server_name)
        

    #if the login fails this will 
    #set the state to username    
    def __testLogin__ (self):
        print "user="+repr(self.user)
        print "pw="+repr(self.pw)
        if self.sman.login(self.user, self.pw):
            self.state = "loggedin"
        else:
            self.state = "username"
